// 获取元素
const table = document.querySelector('.list')
const total = document.querySelector('.total')
const form = document.querySelector('#form')
const submitBtn = document.querySelector('#submit')
//渲染页面
const getStudentList = async () => {
  const { data: res } = await axios({
    url: '/students',
  })
  // console.log(res.data)
  // 渲染页面
  const htmlStr = res.data
    .map((item) => {
      return ` <tr>
    <td>${item.name}</td>
    <td>${item.age}</td>
    <td>${item.gender ? '男' : '女'}</td>
    <td>第${item.group}组</td>
    <td>${item.hope_salary}</td>
    <td>${item.salary}</td>
      </td>
    <td>${item.province + item.city + item.area}</td>
    <td>
      <a href="javascript:;" class="text-success mr-3"
        ><i class="bi bi-pen" data-id = "${item.id}"></i
      ></a>
      <a href="javascript:;" class="text-danger"><i class="bi bi-trash" data-id = "${
        item.id
      }"></i></a>
    </td>
  </tr>`
    })
    .join('')
  table.innerHTML = htmlStr
  total.innerHTML = res.data.length
}
getStudentList()
// 初始化模态框 & 城市选择
// bootstrap的模态框直接cv即可
const modalBox = document.querySelector('#modal')
const modal = new bootstrap.Modal(modalBox)
const ps = document.querySelector('[name=province]')
const cs = document.querySelector('[name=city]')
const as = document.querySelector('[name=area]')
// 显示省市区
const initCity = async () => {
  const { data: res } = await axios({
    url: '/api/province',
  })
  // console.log(res.data)
  const provinceStr = res.list
    .map((item) => {
      return ` <option value="${item}">--${item}--</option>`
    })
    .join('')
  ps.innerHTML = ` <option value="">--省份--</option>${provinceStr}`

  ps.addEventListener('change', async function () {
    cs.innerHTML = `<option value="">--城市--</option>`
    as.innerHTML = ` <option value="">--地区--</option>`

    if (!ps.value) return
    const { data: res } = await axios({
      url: '/api/city',
      params: {
        pname: ps.value,
      },
    })
    const cityStr = res.list
      .map((item) => {
        return ` <option value="${item}">--${item}--</option>`
      })
      .join('')
    cs.innerHTML = ` <option value="">--城市--</option>${cityStr}`
  })
  cs.addEventListener('change', async function () {
    as.innerHTML = ` <option value="">--地区--</option>`
    if (!cs.value) return
    const { data: res } = await axios({
      url: '/api/area',
      params: {
        pname: ps.value,
        cname: cs.value,
      },
    })
    // console.log(res.data)
    const areaStr = res.list
      .map((item) => {
        return ` <option value="${item}">--${item}--</option>`
      })
      .join('')
    as.innerHTML = ` <option value="">--地区--</option>${areaStr}`
  })
}
initCity()
// 弹出模态框
const addBtn = document.querySelector('#openModal')
addBtn.addEventListener('click', function () {
  form.reset()
  modalBox.dataset.id = 'add'
  modalBox.querySelector('.modal-title').innerHTML = '添加学员信息'
  modal.show()
})
//添加
submitBtn.addEventListener('click', async function () {
  const data = serialize(form, { hash: true })
  // if(data.age) return alert('年龄不能为空')
  modalBox.querySelector('#cb01').checked
    ? (data.gender = 1)
    : (data.gender = 0)
  data.age = +data.age
  data.gender = +data.gender
  data.hope_salary = +data.hope_salary
  data.salary = +data.salary
  data.group = +data.group
  if (data.group < 1 || data.gender > 8) return alert('组号只能为1-8')
  if (modalBox.dataset.id === 'add') {
    try {
      const res = await axios({
        url: '/students',
        method: 'post',
        data,
      })
      modal.hide()
      getStudentList()
      alert(res.data.message)
    } catch (error) {
      alert(error)
    }
  } else {
    try {
      const res = await axios({
        url: '/students/' + modalBox.dataset.id,
        method: 'PUT',
        data,
      })
      //关闭modal层
      modal.hide()
      //调用渲染函数重新刷新页面
      getStudentList()
      //提示用户已经修改成功了
      alert(res.data.message)
    } catch (error) {
      alert(error)
    }
  }
})
//事件委托
table.addEventListener('click', async function (e) {
  if (e.target.classList.contains('bi-pen')) {
    let id = e.target.dataset.id
    const { data: res } = await axios({
      url: '/students/' + id,
    })
    // modalBox.querySelector('[name=name').value = res.data.name
    const nodelist = modalBox.querySelectorAll('[name')
    nodelist.forEach((item) => {
      if (item.name === 'gender') {
        res.data[item.name]
          ? (modalBox.querySelector('#cb01').checked = true)
          : (modalBox.querySelector('#cb02 ').checked = true)
      }
      item.value = res.data[item.name]
    })
    // 获取城市列表
    const { data: cityData } = await axios({
      url: '/api/city',
      params: {
        pname: res.data.province,
      },
    })
    // console.log(cityData.data)
    // 渲染下拉菜单选项
    const cityStr = cityData.list
      .map((item) => {
        return ` <option value="${item}">--${item}--</option>`
      })
      .join('')
    cs.innerHTML = ` <option value="">--城市--</option>${cityStr}`
    //赋值
    cs.value = res.data.city
    // 获取地区
    const { data: areaData } = await axios({
      url: '/api/area',
      params: {
        pname: res.data.province,
        cname: res.data.city,
      },
    })
    // console.log(areaData.data)
    //渲染城市下拉框选项
    const areaStr = areaData.list
      .map((item) => {
        return ` <option value="${item}">--${item}--</option>`
      })
      .join('')
    as.innerHTML = ` <option value="">--省份--</option>${areaStr}`
    //赋值
    as.value = res.data.area
     //设置modal层自定义属性，把学生ID给到modal层自定义属性
    modalBox.dataset.id = id
    modalBox.querySelector('.modal-title').innerHTML = '修改学员信息'
    modal.show()
  }
  if (e.target.classList.contains('bi-trash')) {
    const id = e.target.dataset.id
    // 删除
    await axios({
      url: '/students/' + id,
      method: 'DELETE',
    })
    getStudentList()
    alert('删除成功')
  }
})
